<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.2/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"littlefxc.github.io","root":"/","images":"/images","scheme":"Mist","version":"8.2.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}};
  </script>
<meta name="description" content="负载均衡介绍将请求或者说流量，以期望的规则分摊到多个操作单元上进行执行。 通过它可以实现横向扩展(scale out)，将冗余的作用发挥为高可用。另外，还可以物尽其用，提升资源使用率。">
<meta property="og:type" content="article">
<meta property="og:title" content="负载均衡Ribbon">
<meta property="og:url" content="http://littlefxc.github.io/2021/10/21/%E8%B4%9F%E8%BD%BD%E5%9D%87%E8%A1%A1Ribbon/index.html">
<meta property="og:site_name" content="一年春又来">
<meta property="og:description" content="负载均衡介绍将请求或者说流量，以期望的规则分摊到多个操作单元上进行执行。 通过它可以实现横向扩展(scale out)，将冗余的作用发挥为高可用。另外，还可以物尽其用，提升资源使用率。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/image-20211021155325000.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/image-20211021160108842.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/image-20211021160704789.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/5e12e23709f43f6528861210.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/5e12e63009550a2029541170.png">
<meta property="article:published_time" content="2021-10-21T04:01:22.000Z">
<meta property="article:modified_time" content="2022-05-10T01:54:27.073Z">
<meta property="article:author" content="一年春又来">
<meta property="article:tag" content="Ribbon">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/littlefxc/oss/raw/master/images/image-20211021155325000.png">


<link rel="canonical" href="http://littlefxc.github.io/2021/10/21/%E8%B4%9F%E8%BD%BD%E5%9D%87%E8%A1%A1Ribbon/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>
<title>负载均衡Ribbon | 一年春又来</title>
  




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="一年春又来" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">一年春又来</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home"><a href="/" rel="section"><i class="home                          //首页 fa-fw"></i>首页</a></li>
        <li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="archive          //归档 fa-fw"></i>归档</a></li>
        <li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="th           //分类 fa-fw"></i>分类</a></li>
        <li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="tags                     //标签 fa-fw"></i>标签</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E8%B4%9F%E8%BD%BD%E5%9D%87%E8%A1%A1%E4%BB%8B%E7%BB%8D"><span class="nav-text">负载均衡介绍</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%A6%82%E5%BF%B5"><span class="nav-text">概念</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%AE%A2%E6%88%B7%E7%AB%AF%E8%B4%9F%E8%BD%BD%E5%9D%87%E8%A1%A1"><span class="nav-text">客户端负载均衡</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%9C%8D%E5%8A%A1%E7%AB%AF%E8%B4%9F%E8%BD%BD%E5%9D%87%E8%A1%A1"><span class="nav-text">服务端负载均衡</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%8A%80%E6%9C%AF%E9%80%89%E5%9E%8B"><span class="nav-text">技术选型</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%B7%B1%E5%85%A5Ribbon"><span class="nav-text">深入Ribbon</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%B4%9F%E8%BD%BD%E5%9D%87%E8%A1%A1%E7%AD%96%E7%95%A5%E5%92%8C%E5%8E%9F%E7%90%86%EF%BC%8C%E5%8A%A0%E8%BD%BD%E6%96%B9%E5%BC%8F%EF%BC%8CIPing-%E6%9C%BA%E5%88%B6"><span class="nav-text">负载均衡策略和原理，加载方式，IPing 机制</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#LoadBalanced-%E5%8E%9F%E7%90%86%E8%A7%A3%E6%9E%90"><span class="nav-text">LoadBalanced 原理解析</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#LoadBalanced"><span class="nav-text">@LoadBalanced</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#LBAutoConfig"><span class="nav-text">LBAutoConfig</span></a></li></ol></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">一年春又来</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">234</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">38</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">125</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://littlefxc.github.io/2021/10/21/%E8%B4%9F%E8%BD%BD%E5%9D%87%E8%A1%A1Ribbon/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="一年春又来">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="一年春又来">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          负载均衡Ribbon
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2021-10-21 12:01:22" itemprop="dateCreated datePublished" datetime="2021-10-21T12:01:22+08:00">2021-10-21</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2022-05-10 09:54:27" itemprop="dateModified" datetime="2022-05-10T09:54:27+08:00">2022-05-10</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%88%86%E5%B8%83%E5%BC%8F%E7%B3%BB%E7%BB%9F/" itemprop="url" rel="index"><span itemprop="name">分布式系统</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h1 id="负载均衡介绍"><a href="#负载均衡介绍" class="headerlink" title="负载均衡介绍"></a>负载均衡介绍</h1><p>将请求或者说流量，以期望的规则分摊到多个操作单元上进行执行。</p>
<p>通过它可以实现横向扩展(scale out)，将冗余的作用发挥为高可用。另外，还可以物尽其用，提升资源使用率。</p>
<span id="more"></span>

<h2 id="概念"><a href="#概念" class="headerlink" title="概念"></a>概念</h2><h2 id="客户端负载均衡"><a href="#客户端负载均衡" class="headerlink" title="客户端负载均衡"></a>客户端负载均衡</h2><p><img src="https://gitee.com/littlefxc/oss/raw/master/images/image-20211021155325000.png" alt="image-20211021155325000"></p>
<p>基于客户端做负载均衡，有一个前提是需要在客户端本地维护一个服务的机器列表，同时在本地指定一个LB策略，然后输出一个服务。服务列表并不是一成不变的，机器列表需要通过注册中心动态更新机器列表。</p>
<h2 id="服务端负载均衡"><a href="#服务端负载均衡" class="headerlink" title="服务端负载均衡"></a>服务端负载均衡</h2><p><img src="https://gitee.com/littlefxc/oss/raw/master/images/image-20211021160108842.png" alt="image-20211021160108842"></p>
<ul>
<li>大型应用通常是客户端+服务端负载均衡搭配使用</li>
</ul>
<h2 id="技术选型"><a href="#技术选型" class="headerlink" title="技术选型"></a>技术选型</h2><p><img src="https://gitee.com/littlefxc/oss/raw/master/images/image-20211021160704789.png" alt="image-20211021160704789"></p>
<h1 id="深入Ribbon"><a href="#深入Ribbon" class="headerlink" title="深入Ribbon"></a>深入Ribbon</h1><h2 id="负载均衡策略和原理，加载方式，IPing-机制"><a href="#负载均衡策略和原理，加载方式，IPing-机制" class="headerlink" title="负载均衡策略和原理，加载方式，IPing 机制"></a>负载均衡策略和原理，加载方式，IPing 机制</h2><p><img src="https://gitee.com/littlefxc/oss/raw/master/images/5e12e23709f43f6528861210.png"></p>
<p>一个HttpRequest发过来，先被转发到Eureka上。此时Eureka仍然通过服务发现获取了所有服务节点的物理地址，但问题是他不知道该调用哪一个，只好把请求转到了Ribbon手里。</p>
<ul>
<li><p>IPing</p>
<p>IPing是Ribbon的一套healthcheck机制，故名思议，就是要Ping一下目标机器看是否还在线，一般情况下IPing并不会主动向服务节点发起healthcheck请求，Ribbon后台通过静默处理返回true默认表示所有服务节点都处于存活状态（和Eureka集成的时候会检查服节点UP状态）。</p>
<p>IPing 有以下几种方式：</p>
<ul>
<li>DummyPing，默认返回true，即认为所有节点都可用，这也是单独使用Ribbon时的默认模式</li>
<li>NIWSDiscoveryPing，借助Eureka服务发现机制获取节点状态，假如节点状态是UP则认为是可用状态</li>
<li>PingUrl，它会主动向服务节点发起一次http调用，如果对方有响应则认为节点可用</li>
</ul>
<p>第三种方式 PingUrl 比较生猛，会对各个服务节点请求个不停，各个节点有可能扛不住压力，因此除非特殊指定，在和Eureka合作时，一般采用第二种方式。</p>
</li>
<li><p>IRule</p>
<p>这就是Ribbon的组件库了，各种负载均衡策略都继承自IRule接口。所有经过Ribbon的请求都会先请示IRule一把，找到负载均衡策略选定的目标机器，然后再把请求转发过去。</p>
</li>
</ul>
<h2 id="LoadBalanced-原理解析"><a href="#LoadBalanced-原理解析" class="headerlink" title="LoadBalanced 原理解析"></a>LoadBalanced 原理解析</h2><p><img src="https://gitee.com/littlefxc/oss/raw/master/images/5e12e63009550a2029541170.png"></p>
<h3 id="LoadBalanced"><a href="#LoadBalanced" class="headerlink" title="@LoadBalanced"></a>@LoadBalanced</h3><p>这个注解一头挂在<code>RestTemplate</code>上，另一头挂在<code>LoadBalancerAutoConfiguration</code>这个类上。它就像连接两个世界的传送门，将所有顶着「LoadBalanced」注解的RestTemplate类，都传入到<code>LoadBalancerAutoConfiguration</code>中。如果要深挖底层的作用机制，大家可以发现这个注解的定义上还有一个<code>@Qualifier</code>注解。@Qualifier注解搭配@Autowired注解做自动装配，可以通过name属性，将指定的Bean装载到指定位置（即使有两个同样类型的Bean，也可以通过Qualifier定义时声明的name做区分）。这里「LoadBalanced」也是借助Qualifier实现了一个给RestTemplate打标签的功能，凡是被打标的RestTemplate都会被传送到AutoConfig中做进一步改造。</p>
<h3 id="LBAutoConfig"><a href="#LBAutoConfig" class="headerlink" title="LBAutoConfig"></a>LBAutoConfig</h3><p>从前一步中传送过来的RestTemplate，会经过<code>LBAutoConfig</code>的装配，将一系列的<code>Interceptor</code>（拦截器）添加到RestTemplate中。拦截器是类似职责链编程模型的结构，我们常见的ServletFilter，权限控制器等，都是类似的模式。Ribbon拦截器会拦截每个网络请求做一番处理，在这个过程中拦截器会找到对应的LoadBalancer对HTTP请求进行接管，接着LoadBalancer就会找到默认或指定的负载均衡策略来对HTTP请求进行转发。</p>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Ribbon/" rel="tag"># Ribbon</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2021/10/19/%E7%BD%91%E7%BB%9C%E5%9F%BA%E7%A1%80%E6%A6%82%E8%BF%B0/" rel="prev" title="网络基础概述">
                  <i class="fa fa-chevron-left"></i> 网络基础概述
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2021/12/06/%E6%8E%A5%E5%8F%A3%E5%B9%82%E7%AD%89%E6%80%A7/" rel="next" title="接口幂等性">
                  接口幂等性 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>







<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">一年春又来</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/mist/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  
<script src="/js/local-search.js"></script>






  





</body>
</html>
